/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sqlserver;

import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;

/**
 *
 * @author ROMANCE
 */
import java.util.ArrayList;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Insert {
/*<<<<<<< .mine*/
    public static int execute_syntax_command (String command, String dbName)
	{
            StringTokenizer st=new StringTokenizer(command.toLowerCase()," ,");
            int state=0;//0=select;1=from;2=where
            ArrayList<String> into=new ArrayList<String>();
            ArrayList<String> insert=new ArrayList<String>();
            while (st.hasMoreTokens()){
                  String theToken=st.nextToken();
                  System.out.println("Token:"+theToken);

                  if (theToken.equals("into"))state=0;
                  else if (theToken.equals("insert"))state=1;
                  else {
                        if (state==0)into.add(theToken);
                        if (state==1)insert.add(theToken);
                  }
            }
            String [] intoitem = into.toArray(new String[0]);
            
            for(int i = 0; i< into.size(); i++)
            {
                intoitem[i] = Utils.replaceAll(intoitem[i], "(", "");
                intoitem[i] = Utils.replaceAll(intoitem[i], ")", "");
                intoitem[i] = Utils.replaceAll(intoitem[i], "'", "");
            }
            for(int i = 0; i< into.size(); i++)
            {
                System.out.println("intoitem insert: " + intoitem[i]);
            }
            
            ArrayList<String> column = new ArrayList<String>();
            ArrayList<String> value = new ArrayList<String>();
            String[] syntax_arr = command.split(" ");
            //String tableName = "";
            String tableName = intoitem[0];
            int i_values = 0;
            for(int i = 0; i< into.size(); i++)
            {
                if(intoitem[i].compareTo("values") == 0)
                {
                    i_values = i;
                }
            }
            
            if(i_values != 0)
            {
                for(int i= 1; i< i_values; i++)
                {
                    //if(intoitem[i].compareTo("(") != 0 && intoitem[i].compareTo(")") != 0)
                    //{
                        column.add(intoitem[i]);
                    //}
                }
                for(int i = i_values + 1; i < into.size(); i++)
                {
                    //if(intoitem[i].compareTo("(") != 0 && intoitem[i].compareTo(")") != 0)
                    //{
                        value.add(intoitem[i]);
                    //}
                }
            }
            System.out.println(dbName);
            System.out.println(tableName);
            System.out.println(i_values);
            System.out.println(column.toString());
            System.out.println(value.toString());
            //here the vectors select, from and where have what you are looking for
            System.out.println("NR of TOKEN IN into:"+ into.toString());
            return execute_command(dbName, tableName, column.toArray(new String[0]), value.toArray(new String[0]));
	}
 
   /* public static final String INSERT = "insert";
    private static final String QUOTE_ESCAPE = "''";
    private static final String COMMA_ESCAPE = "~#####1~";*/
/*>>>>>>> .r16

    static void execute_syntax_command(String command, String database) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
    
<<<<<<< .mine*/
    public static int execute_command(String dbName, String tableName, String[] columns, String[] values)
	{
		Document doc = MetaManipulation.load_doc(dbName, tableName);
		if (doc == null)
			return MetaManipulation.ErrorLoading;
		
		if (MetaManipulation.CheckNodeExists(dbName, tableName) == false)
		{
			Element rootElement = doc.getDocumentElement();
			
			Element tb = doc.createElement("table");
			
			Attr attr = doc.createAttribute("name");
			attr.setValue(tableName);
			tb.setAttributeNode(attr);
			
			rootElement.appendChild(tb);
			
			MetaManipulation.save_doc(doc, dbName);
		}
		
		doc = MetaManipulation.load_doc(dbName, tableName);
		if (doc == null)
			return MetaManipulation.ErrorLoading;
		
		try
		{
			XPath xpath = XPathFactory.newInstance().newXPath();
			XPathExpression expr = xpath.compile("//table[@name='"
					+ tableName + "']");
			
			Element tbNode = (Element) expr.evaluate(doc, XPathConstants.NODE);
			Element newRwNode = doc.createElement("row");
			
			for(int i = 0; i < columns.length; i++)
			{
				Element cols = doc.createElement("column");
				
				Element name = doc.createElement("name");
				name.setTextContent(columns[i]);
				
				cols.appendChild(name);
				
				
				Element value = doc.createElement("value");
				value.setTextContent(values[i]);
				
				cols.appendChild(value);
				
				
				newRwNode.appendChild(cols);
			}
			
			tbNode.appendChild(newRwNode);
		}
		catch (Exception e) {
			return MetaManipulation.ErrorUnknown;
		}
		
		if (MetaManipulation.save_doc(doc, dbName) == MetaManipulation.Success) {
			return MetaManipulation.Success;
		} else {
			return MetaManipulation.ErrorUnknown;
		}
	}
    /*private ArrayList binaryStreamObjectList = new ArrayList();

    public String tableName;

    public String whereStatement;

    public String sqlType;

    public String[] columnNames;

    public String[] columnValues;

    public String[] columnWhereNames;

    public String[] columnWhereValues;

    public String getTableName() {
        return tableName;
    }

    public String[] getColumnNames() {
        return columnNames;
    }

    public String[] getWhereColumnNames() {
        return columnWhereNames;
    }

    public String[] getWhereColumnValues() {
        return columnWhereValues;
    }

    public String[] getColumnValues() {
        return columnValues;
    }
    
    public void parse(String sql) throws Exception {
    sql = sql.trim();
    tableName = null;
    columnNames = new String[0];
    columnValues = new String[0];
    columnWhereNames = new String[0];
    columnWhereValues = new String[0];
    whereStatement = null;
    sqlType = null;
    sql = sql.trim();

//replace comma(,) in values between quotes(')
    StringTokenizer tokQuote = new StringTokenizer(sql.toString(), "'", true);
    StringBuilder sb = new StringBuilder();
    boolean openParent1 = false;
    while (tokQuote.hasMoreTokens()) {
      String next = tokQuote.nextToken();
      if (openParent1)
        next = Utils.replaceAll(next, ",", COMMA_ESCAPE);
      sb.append(next);
      if (next.equalsIgnoreCase("'")) {
        if (openParent1 == true)
          openParent1 = false;
        else
          openParent1 = true;
      }
    }
//END replacement
    sql = sb.toString();
    String upperSql = sql.toUpperCase();


//handle unsupported statements
    if (upperSql.startsWith("ALTER "))
      throw new Exception("ALTER TABLE statements are not supported.");
    if (upperSql.startsWith("DROP "))
      throw new Exception("DROP statements are not supported.");


//INSERT
    if ( upperSql.startsWith("INSERT ") ) {
      if (upperSql.lastIndexOf(" VALUES") == -1) {
          throw new Exception("Malformed SQL. Missing VALUES statement.");
        }
        sqlType = INSERT;
        int intoPos = 0;
        if (upperSql.indexOf(" INTO ") != -1)
          intoPos = upperSql.indexOf(" INTO ") + 6;
        else
          intoPos = upperSql.indexOf("INSERT ") + 7;
        int bracketPos = upperSql.indexOf("(");
        int lastBracketPos = upperSql.indexOf(")");
        tableName = sql.substring(intoPos, bracketPos).trim();

        Vector cols = new Vector();
        StringTokenizer tokenizer = new StringTokenizer(upperSql.substring(
            bracketPos + 1, lastBracketPos), ",");
        while (tokenizer.hasMoreTokens()) {
          cols.add(tokenizer.nextToken().trim());
        }
        columnNames = new String[cols.size()];
        cols.copyInto(columnNames);

        int valuesPos = upperSql.indexOf("VALUES");
        String endStatement = sql.substring(valuesPos + 6).trim();
        bracketPos = endStatement.indexOf("(");
        lastBracketPos = endStatement.lastIndexOf(")");
        Vector values = new Vector();
        StringTokenizer tokenizer2 = new StringTokenizer(endStatement.substring(
            bracketPos + 1, lastBracketPos), ",");
        while (tokenizer2.hasMoreTokens()) {
          String value = tokenizer2.nextToken().trim();
          value = Utils.handleQuotedString(value);
          value = Utils.replaceAll(value, COMMA_ESCAPE, ",");
          value = Utils.replaceAll(value, QUOTE_ESCAPE, "'");
          values.add(value);
        }
        columnValues = new String[values.size()];
        values.copyInto(columnValues);
    }

    }*/

}
